package com.coocaa.ops.admin.v1.globalparams.service;

import com.coocaa.ops.admin.base.language.CommonLanguageProperties;
import com.coocaa.ops.common.core.biz.auth.entity.SysUserEntity;
import com.coocaa.ops.admin.v1.globalparams.biz.GlobalParamsBizImpl;
import com.coocaa.ops.admin.v1.globalparams.biz.IGlobalParamsContentBiz;
import com.coocaa.ops.admin.v1.globalparams.converter.GlobalParamsBeanConverter;
import com.coocaa.ops.admin.v1.globalparams.converter.GlobalParamsQueryConverter;
import com.coocaa.ops.admin.v1.globalparams.model.GlobalParamsModel;
import com.coocaa.ops.admin.v1.globalparams.model.GlobalParamsPageListModel;
import com.coocaa.ops.common.core.base.enums.ResourceTypeEnum;
import com.coocaa.ops.common.core.base.model.PageResultModel;
import com.coocaa.ops.common.core.base.model.R;
import com.coocaa.ops.common.core.base.mybatis.UpdateTemplate;
import com.coocaa.ops.common.core.biz.cache.service.MultiCenterCacheUpdateService;
import com.coocaa.ops.common.core.biz.globalparams.entity.GlobalParamsContentEntity;
import com.coocaa.ops.common.core.biz.globalparams.entity.GlobalParamsEntity;
import com.coocaa.ops.common.tool.exception.BusinessException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author : hql
 * @date : 2020/7/14 15:03
 * @description
 */
@Service
public class GlobalParamsServiceImpl implements IGlobalParamsService {
    private static CommonLanguageProperties commonLanguageProperties;
    private static final int MAX_PARAMS_NUM = 5;

    @Autowired
    private GlobalParamsBizImpl globalParamsBiz;
    @Autowired
    private IGlobalParamsContentBiz globalParamsContentBiz;
    @Autowired
    private MultiCenterCacheUpdateService myUpdateCacheService;

    @Override
    public void save(GlobalParamsModel model, Integer userId) {
        GlobalParamsEntity entity = GlobalParamsBeanConverter.convertGlobalParams(model);
        if (entity.getId() == null) {
            //处理新增
            entity = this.handleNewAdd(entity, userId);
        } else {
            //处理更新
            this.handleUpdate(entity, userId);
        }
        myUpdateCacheService.updateMultiCenterCache(entity.getId(), ResourceTypeEnum.PARAMS.getValue());
    }

    @Override
    public PageResultModel<GlobalParamsPageListModel> getPageList(GlobalParamsModel model) {
        Map<String, Object> params = GlobalParamsQueryConverter.getQueryParams(model);
        int total = globalParamsBiz.getMapper().selectCountPage(params);
        if (total > 0) {
            List<GlobalParamsEntity> globalParamsList = globalParamsBiz.getGlobalParamsList(params);
            return GlobalParamsBeanConverter.convertPageList(total, globalParamsList);
        }
        return PageResultModel.getPageResultModel(total, new ArrayList<>());
    }

    @Override
    public R deleteBatch(List<Integer> ids, SysUserEntity currentUser) {
        UpdateTemplate<GlobalParamsEntity> wrapper = UpdateTemplate.getUpdateTemplate();
        wrapper.in("`id`", ids);
        GlobalParamsEntity update = new GlobalParamsEntity();
        update.setFlag(0);
        update.setModifier(currentUser.getId());
        globalParamsBiz.getMapper().update(update, wrapper);
        myUpdateCacheService.updateMultiCenterCache(0, ResourceTypeEnum.PARAMS.getValue());
        return R.ok().msg(commonLanguageProperties.getDeleteSuccess());
    }

    @Autowired
    public void setCommonLanguageProperties(CommonLanguageProperties commonLanguageProperties) {
        GlobalParamsServiceImpl.commonLanguageProperties = commonLanguageProperties;
    }

    private void handleUpdate(GlobalParamsEntity entity, Integer userId) {
        List<Integer> globalParamsIds = globalParamsBiz.getMapper().getUsableParamsIdsWithPolicy();
        if (CollectionUtils.isNotEmpty(globalParamsIds)) {
            if (globalParamsIds.size() >= MAX_PARAMS_NUM
                    && !globalParamsIds.contains(entity.getId())
                    && Objects.equals(entity.getSwitchStatus(), 1)
                    && isDmpParams(entity)) {
                throw new BusinessException(null, "保存失败：可同时支持的带策略下发参数已达到5个");
            }
        }
        if (globalParamsBiz.isRemarkExist(entity.getRemark(), entity.getId())) {
            throw new BusinessException(null, "保存失败：该标记" + entity.getRemark() + "已存在");
        }
        entity.setModifier(userId);
        globalParamsBiz.updateGlobalParams(entity);
        globalParamsContentBiz.deleteRlsContent(entity.getId());
        this.saveRls(entity);
    }

    private GlobalParamsEntity handleNewAdd(GlobalParamsEntity entity, Integer userId) {
        if (Objects.equals(entity.getSwitchStatus(), 1)) {
            List<Integer> globalParamsIds = globalParamsBiz.getMapper().getUsableParamsIdsWithPolicy();
            if (globalParamsIds.size() >= MAX_PARAMS_NUM && isDmpParams(entity)) {
                throw new BusinessException(null, "保存失败：可同时支持的带策略下发参数已达到5个");
            }
            if (globalParamsBiz.isRemarkExist(entity.getRemark(), null)) {
                throw new BusinessException(null, "保存失败：该标记" + entity.getRemark() + "已存在");
            }
        }
        entity.setCreator(userId);
        entity.setModifier(userId);
        GlobalParamsEntity saveResult = globalParamsBiz.addGlobalParams(entity);
        this.saveRls(saveResult);
        return saveResult;
    }

    private void saveRls(GlobalParamsEntity saveResult) {
        Integer globalParamsId = saveResult.getId();
        List<GlobalParamsContentEntity> contentList = saveResult.getGlobalParamsContent();
        if (CollectionUtils.isNotEmpty(contentList)) {
            for (GlobalParamsContentEntity contentEntity : contentList) {
                contentEntity.setGlobalParamsId(globalParamsId);
                String params = contentEntity.getParams();
                contentEntity.setParams(StringEscapeUtils.unescapeJava(params));
            }
            globalParamsContentBiz.saveBatchContents(contentList);
        }
    }

    /**
     * 判断是否配置了dmp
     *
     * @param entity
     * @return
     */
    private boolean isDmpParams(GlobalParamsEntity entity) {
        List<GlobalParamsContentEntity> globalParamsContentList = entity.getGlobalParamsContent();
        if (CollectionUtils.isNotEmpty(globalParamsContentList)) {
            for (GlobalParamsContentEntity paramsContentEntity : globalParamsContentList) {
                if (paramsContentEntity.getDmpPolicyId() != null) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    }


}
